""" 

    Friends.py used in RepresentedBy Facebook application
    http://apps.facebook.com/representedby/
    
    This page just shows all of your friends and which legislators they have.  If a friend is 
    not a user of the RepresentedBy app, then we just try to guess the legislator based on 
    location information in their Facebook profile.  For most people, this means we can get
    senator information, but not representative information
    
"""

__author__ = "Will Turnage (will@wubbahed.com)"
__version__ = "0.1.0"
__copyright__ = "Copyright (c) 2009 wubbahed.com"
__license__ = "GPLv3"


import os
import wsgiref.handlers
import facebook
import const
import string

from sets import Set
from django.utils import simplejson
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import urlfetch
from google.appengine.ext import db
from utils import fbUtil, dbUtil, UserDistrict, SunlightUtil

class MainHandler(webapp.RequestHandler):
    def post(self):
        
        try:
            
            #check if Facebook app is installed
            self.facebookapi = fbUtil().checkFacebookAppInstalled(self, True, "friends")
            if self.facebookapi is None:
                return

            myvars = {"section": "goodies"}
            profiletab = self.request.get('tab', default_value=None)
            if profiletab is None:
                path = os.path.join(os.path.dirname(__file__), '../templates/heading.fbml')
                self.response.out.write(template.render(path, myvars))
            
            
            friend_ids = self.facebookapi.friends.get()
            if friend_ids is None:
                friend_ids = [self.facebookapi.uid]
            elif len(friend_ids) == 0:
                friend_ids = [self.facebookapi.uid]
            else:
                friend_ids.append(self.facebookapi.uid)
                
            friends_with_app_ids = self.facebookapi.friends.getAppUsers()
            if friends_with_app_ids is None:
                friends_with_app_ids = [self.facebookapi.uid]
            elif len(friends_with_app_ids) == 0:
                friends_with_app_ids = [self.facebookapi.uid]
            else:
                friends_with_app_ids.append(self.facebookapi.uid)
  
            rep_set = {}
            states = {}
            sen_set = Set([])
            results = []
            if friends_with_app_ids is not None:
                if len(friends_with_app_ids) > 0:
                    for friend in friends_with_app_ids:
                        query = UserDistrict.all()
                        query.filter("uid =", friend)
                        results = query.fetch(1)
            
                        for result in results:
                            friend_ids.remove(str(result.uid))
                            if result.rep:
                                if rep_set.has_key(result.rep):
                                    rep_set[result.rep].append(result.uid)
                                    # rep_set[result.rep]["friends"] = rep_set[result.rep]["friends"]+ 1
                                else:
                                    rep_set[result.rep] = [[{"id": result.rep, "name": const.FRIENDLY_NAME[result.rep]}], result.uid]
                                    # rep_set[result.rep] = {"id": result.rep, "name": const.FRIENDLY_NAME[result.rep], "friends": 1}
                            if result.state:
                                if states.has_key(result.state):
                                    states[result.state].append(result.uid)
                                    # states[result.state]["friends"] = states[result.state]["friends"]+ 1
                                else:
                                    states[result.state] = [[], result.uid]
                                    # states[result.state] = {"state": result.state, "friends": 1, "senators":[]}
                                    for senator in const.LEGISLATORS_BY_STATE[result.state]["senators"]:
                                         sen_set.add(senator)
                                         states[result.state][0].append({"id": senator, "name": const.FRIENDLY_NAME[senator]})
                                    #     states[result.state]["senators"].append({"id": senator, "name": const.FRIENDLY_NAME[senator]})
                                              
            friends_loc = self.facebookapi.users.getInfo(friend_ids, ['uid', 'current_location'])  
            #for all your other friends, try and look up their information
            for friend in friends_loc :
                if friend:
                    sunlight = SunlightUtil(const.SUNLIGHT_API_KEY)
                    friendInfo = sunlight.getDistrictForUser(friend["uid"], friend["current_location"])
                    if friendInfo is not None:
                        if (friendInfo.has_key("state")):
                            if states.has_key(friendInfo["state"]):
                                # states[friendInfo["state"]]["friends"] = states[friendInfo["state"]]["friends"]+ 1
                                states[friendInfo["state"]].append(friend["uid"])
                            else:                
                                states[friendInfo["state"]] = [[], friend["uid"]]
                                # states[friendInfo["state"]] = {"state": friendInfo["state"], "friends": 1, "senators":[]}
                                for senator in const.LEGISLATORS_BY_STATE[friendInfo["state"]]["senators"]:
                                    sen_set.add(senator)
                                    states[friendInfo["state"]][0].append({"id": senator, "name": const.FRIENDLY_NAME[senator]})
                                    # states[friendInfo["state"]]["senators"].append({"id": senator, "name": const.FRIENDLY_NAME[senator]})

                            row = sunlight.getLegislatorsFromLocationRow(friendInfo)
                            if row.has_key("rep"):
                                if rep_set.has_key(row["rep"]):
                                    rep_set[row["rep"]].append(friend["uid"])
                                    # rep_set[row["rep"]]["friends"] = rep_set[row["rep"]]["friends"] + 1
                                else:
                                    rep_set[row["rep"]] = [[{"id": row["rep"], "name": const.FRIENDLY_NAME[row["rep"]]}], friend["uid"] ]
                                    # rep_set[row["rep"]] = {"id": row["rep"], "name": const.FRIENDLY_NAME[row["rep"]], "friends": 1}
                                                           
                        
            percent_data = {}
            
            percent_data["friend_reps"] = rep_set.values()
            percent_data["friend_sen"] = states.values()
            
            percent_data["house_total"] = len(const.REPRESENTATIVES)
            percent_data["sen_total"] = len(const.SENATORS)
            percent_data["house_count"] = len(rep_set)
            percent_data["sen_count"] = len(sen_set)
            
            
            path = os.path.join(os.path.dirname(__file__), '../templates/friends.fbml')
            self.response.out.write(template.render(path, percent_data ))
            
        except urlfetch.DownloadError, e:
            path = os.path.join(os.path.dirname(__file__), '../templates/error.fbml')
            self.response.out.write(template.render(path, {"error":"Sorry, Google AppEngine ain't working"}))
            
        except facebook.FacebookError, e:
            path = os.path.join(os.path.dirname(__file__), '../templates/error.fbml')
            self.response.out.write(template.render(path, {"error":"Sorry, Facebook ain't working - " + str(e.msg)}))                      
  
def main():
	application = webapp.WSGIApplication([('/fb/friends', MainHandler)],
									   debug=True)
	run_wsgi_app(application)

# load our custom filters		   
webapp.template.register_template_library('customfilters')

if __name__ == '__main__':
	main()
